<template>
	<view class="result-container">
		<!-- 导航栏 -->
		<uv-navbar title="" :border="false" :autoBack="true" :placeholder="true" leftIcon="arrow-left"
			:titleStyle="{ color: '#333' }">
			<template #center>
				<view class="nav-title">考试结果分析</view>
			</template>
		</uv-navbar>

		<!-- 顶部成绩卡片 -->
		<view class="score-card">
			<image class="score-bg"
				src="https://img.freepik.com/free-vector/abstract-blue-geometric-shapes-background_1035-17545.jpg?w=2000"
				mode="aspectFill"></image>
			<view class="score-content">
				<view class="score-title">您的得分</view>
				<view class="score-value">{{ examResult.score || 0 }}<text class="score-total">/{{ examResult.totalScore
					|| 100
				}}</text></view>
				<view class="score-percent">{{ examResult.scorePercent || 0 }}%</view>
				<view class="score-rank" v-if="examResult.rank">
					<text class="rank-label">排名：</text>
					<text class="rank-value">{{ examResult.rank }}</text>
				</view>
			</view>
		</view>

		<!-- 分析概览 -->
		<view class="analysis-overview">
			<view class="overview-title">
				<image class="title-icon" src="https://cdn-icons-png.flaticon.com/512/1584/1584892.png"
					mode="aspectFit">
				</image>
				<text>答题概览</text>
			</view>
			<view class="overview-cards">
				<view class="overview-card">
					<text class="card-value">{{ examResult.totalQuestions || 0 }}</text>
					<text class="card-label">总题数</text>
				</view>
				<view class="overview-card">
					<text class="card-value">{{ examResult.correctCount || 0 }}</text>
					<text class="card-label">答对题数</text>
				</view>
				<view class="overview-card">
					<text class="card-value">{{ examResult.wrongCount || 0 }}</text>
					<text class="card-label">答错题数</text>
				</view>
				<view class="overview-card">
					<text class="card-value">{{ examResult.accuracy || '0%' }}</text>
					<text class="card-label">正确率</text>
				</view>
			</view>
		</view>

		<!-- 答题时间分析 -->
		<view class="time-analysis">
			<view class="section-title">
				<image class="title-icon" src="https://cdn-icons-png.flaticon.com/512/2972/2972531.png"
					mode="aspectFit">
				</image>
				<text>答题时间分析</text>
			</view>
			<view class="chart-container">
				<view class="chart-wrapper" id="timeChart"></view>
				<view class="time-stats">
					<view class="time-stat-item">
						<text class="stat-label">总用时：</text>
						<text class="stat-value">{{ formatTime(examResult.totalTime) }}</text>
					</view>
					<view class="time-stat-item">
						<text class="stat-label">平均每题用时：</text>
						<text class="stat-value">{{ formatTime(examResult.avgTime) }}</text>
					</view>
					<view class="time-stat-item">
						<text class="stat-label">最长用时题目：</text>
						<text class="stat-value">第{{ examResult.maxTimeQuestion }}题 ({{ formatTime(examResult.maxTime)
						}})</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 题型分析 -->
		<view class="question-type-analysis">
			<view class="section-title">
				<image class="title-icon" src="https://cdn-icons-png.flaticon.com/512/2641/2641409.png"
					mode="aspectFit">
				</image>
				<text>题型分析</text>
			</view>
			<view class="chart-container">
				<view class="chart-wrapper" id="typeChart"></view>
			</view>
		</view>

		<!-- 能力雷达图 -->
		<view class="ability-analysis">
			<view class="section-title">
				<image class="title-icon" src="https://cdn-icons-png.flaticon.com/512/1087/1087927.png"
					mode="aspectFit">
				</image>
				<text>AI能力分析</text>
			</view>
			<view class="chart-container">
				<view class="chart-wrapper" id="radarChart"></view>
			</view>
						<view class="ability-list">
							<view class="ability-item" v-for="value in examResult.abilityData" :key="value.name">
								<view class="ability-header">
									<text class="ability-name">{{ value.name }}</text>
									<text class="ability-score">{{ value.score }}</text>
								</view>
								<view class="ability-bar-bg">
									<view class="ability-bar" :style="{ width: value.score + '%', background: getAbilityColor(value.name) }"></view>
								</view>
								<view class="ability-desc" v-if="value.describe">{{ value.describe }}</view>
							</view>
						</view>
		</view>

		<!-- AI分析建议 -->
		<view class="ai-suggestion">
			<view class="section-title">
				<image class="title-icon" src="https://cdn-icons-png.flaticon.com/512/8637/8637922.png"
					mode="aspectFit">
				</image>
				<text>AI学习建议</text>
			</view>
			<view class="suggestion-content">
				<image class="ai-avatar" src="https://cdn-icons-png.flaticon.com/512/4712/4712027.png" mode="aspectFit">
				</image>
				<view class="suggestion-text">
					<view class="suggestion-item" v-for="(item, index) in examResult.aiSuggestions" :key="index">
						<text class="suggestion-point">{{ index + 1 }}. {{ item }}</text>
					</view>
					<view class="suggestion-summary" v-if="examResult.aiSummary">
						<text>{{ examResult.aiSummary }}</text>
					</view>
				</view>
			</view>
			<view class="ai-chat-btn-container">
				<view class="ai-chat-btn" @click="goToChat">
					<image class="chat-icon" src="https://cdn-icons-png.flaticon.com/512/2040/2040946.png" mode="aspectFit">
					</image>
					<text>与AI对话</text>
				</view>
			</view>
		</view>

		<!-- 错题分析 -->
		<view class="wrong-questions" v-if="examResult.wrongQuestions && examResult.wrongQuestions.length > 0">
			<view class="section-title">
				<image class="title-icon" src="https://cdn-icons-png.flaticon.com/512/1828/1828843.png"
					mode="aspectFit">
				</image>
				<text>错题分析</text>
			</view>
			<view class="wrong-list">
				<view class="wrong-item" v-for="(item, index) in examResult.wrongQuestions" :key="index">
					<view class="wrong-title">
						<text class="wrong-number">{{ index + 1 }}. </text>
						<!-- <text>{{ item.title }}</text> -->
						<PraseContent :contents="formatTitle(item.title)" />
					</view>
					<view class="wrong-analysis">
						<text class="analysis-label">正确答案：</text>
						<text class="analysis-content">{{ item.answer }}</text>
					</view>
					<view class="wrong-analysis">
						<text class="analysis-label">您的答案：</text>
						<text class="analysis-content wrong">{{ item.userAnswer }}</text>
					</view>
					<view class="wrong-analysis">
						<text class="analysis-label">解析：</text>
						<text class="analysis-content">{{ item.explanation }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-actions">
			<view class="action-btn share-btn" @click="shareResult">
				<text class="btn-icon">分享</text>
			</view>
			<view class="action-btn home-btn" @click="goHome">
				<text class="btn-icon">返回首页</text>
			</view>
		</view>
	</view>
</template>

<script>
import * as echarts from 'echarts/core';
import { BarChart, LineChart, PieChart, RadarChart } from 'echarts/charts';
import {
	TitleComponent,
	TooltipComponent,
	GridComponent,
	DatasetComponent,
	TransformComponent,
	LegendComponent
} from 'echarts/components';
import PraseContent from '@/components/topic/PraseContent.vue';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
	TitleComponent,
	TooltipComponent,
	GridComponent,
	DatasetComponent,
	TransformComponent,
	LegendComponent,
	LabelLayout,
	UniversalTransition,
	CanvasRenderer,
	BarChart,
	LineChart,
	PieChart,
	RadarChart
]);

export default {
	components: {
		PraseContent
	},
	data() {
		return {
			examId: '',
			examResult: {
				// 基本信息
				score: 85,
				totalScore: 100,
				scorePercent: 85,
				rank: '前10%',

				// 答题概览
				totalQuestions: 20,
				correctCount: 17,
				wrongCount: 3,
				accuracy: '85%',

				// 时间分析
				totalTime: 1800, // 秒
				avgTime: 90, // 秒
				maxTime: 180, // 秒
				maxTimeQuestion: 5,
				timeData: [120, 85, 90, 75, 180, 95, 60, 70, 85, 95, 100, 65, 75, 90, 110, 80, 75, 90, 85, 70],

				// 题型分析
				typeData: [
					{ name: '单选题', total: 10, correct: 9, accuracy: '90%' },
					{ name: '多选题', total: 5, correct: 4, accuracy: '80%' },
					{ name: '判断题', total: 3, correct: 3, accuracy: '100%' },
					{ name: '填空题', total: 2, correct: 1, accuracy: '50%' }
				],

				// 能力分析
				abilityData: [
					{ name: '记忆力', score: 90 },
					{ name: '理解力', score: 85 },
					{ name: '应用能力', score: 80 },
					{ name: '分析能力', score: 75 },
					{ name: '评价能力', score: 70 },
					{ name: '创造能力', score: 65 }
				],

				// AI建议
				aiSuggestions: [
					'加强对填空题的练习，这是您的薄弱环节',
					'多选题需要更加仔细审题，避免遗漏选项',
					'建议复习第5题相关知识点，这是您用时最长的题目'
				],
				aiSummary: '总体表现优秀，建议针对薄弱环节进行有针对性的复习，可以进一步提高成绩。',

				// 错题分析
				wrongQuestions: [
					{
						title: '在计算机系统的多层次结构中，处于硬联逻辑与传统机器（机器指令语言）之间的是？',
						answer: 'B. 微程序机器',
						userAnswer: 'C. 汇编语言机器',
						explanation: '计算机系统的多层次结构从底层到高层依次是：硬联逻辑层、微程序机器层、传统机器层、操作系统层、汇编语言层、高级语言层。'
					},
					{
						title: '以下哪项不是操作系统的基本功能？',
						answer: 'D. 程序编译',
						userAnswer: 'A. 处理机管理',
						explanation: '操作系统的基本功能包括处理机管理、存储器管理、设备管理和文件管理，程序编译是由编译程序完成的。'
					},
					{
						title: '在TCP/IP协议中，负责端到端通信的是哪一层？',
						answer: 'B. 传输层',
						userAnswer: 'C. 网络层',
						explanation: 'TCP/IP协议中，传输层负责端到端的通信，而网络层负责主机到主机的通信。'
					}
				]
			},
			charts: {}
		}
	},
	onLoad(options) {
		if (options.id) {
			this.examId = options.id;
			console.log("请求", this.examId);

			this.getExamResult();
		}
	},
	onReady() {
		// this.$nextTick(() => {
		// 	setTimeout(() => {
		// 		this.initCharts();
		// 	}, 300);
		// });
	},
	methods: {
		// 获取考试结果
		getExamResult() {
			// 这里应该调用API获取真实数据
			// this.$api('getExamResult', { userExamId: this.examId })
			// .then(res => {
			//   if(res.code == 200){
			//     this.examResult = res.data;
			//     this.initCharts();
			//   }
			// })

			// 模拟数据已在data中设置
			this.$api('getExamResult', { userExamID: this.examId }).then(res => {
				if (res.code == 200) {
					console.log(res.data);

					this.examResult = res.data;
					this.initCharts();
				}
			});
			// console.log('获取考试结果:', response);
			// console.log('获取考试ID:', this.examId);
		},

		// 初始化所有图表
		initCharts() {
			this.initTimeChart();
			this.initTypeChart();
			this.initRadarChart();
		},

		// 根据能力名称返回不同颜色
		getAbilityColor(name) {
			const colors = {
				'记忆力': '#1890ff',
				'理解力': '#52c41a',
				'应用能力': '#faad14',
				'分析能力': '#722ed1',
				'评价能力': '#eb2f96',
				'创造能力': '#13c2c2',
			};
			return colors[name] || '#1890ff';
		},

		// 初始化时间分析图表
		initTimeChart() {
			const chartDom = document.getElementById('timeChart');
			if (!chartDom) return;

			this.charts.timeChart = echarts.init(chartDom);

			const labels = this.examResult.timeData.map((_, index) => `第${index + 1}题`);
			const option = {
				color: ['#1890ff'],
				title: {
					text: '每题用时分析(秒)',
					left: 'center',
					textStyle: {
						fontSize: 14
					}
				},
				tooltip: {
					trigger: 'axis',
					formatter: '{b}: {c}秒'
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				xAxis: {
					type: 'category',
					data: labels,
					axisLabel: {
						interval: 1,
						rotate: 45
					}
				},
				yAxis: {
					type: 'value',
					name: '用时(秒)'
				},
				series: [{
					name: '用时',
					type: 'bar',
					data: this.examResult.timeData,
					itemStyle: {
						color: '#1890ff'
					}
				}]
			};

			this.charts.timeChart.setOption(option);
		},
		initTypeChart() {
			const chartDom = document.getElementById('typeChart');
			if (!chartDom) return;

			this.charts.typeChart = echarts.init(chartDom);

			const typeNames = this.examResult.typeData.map(item => item.name);
			const totalData = this.examResult.typeData.map(item => item.total);
			const correctData = this.examResult.typeData.map(item => item.correct);

			const option = {
				color: ['#52c41a', '#1890ff'],
				title: {
					text: '题型正确率分析',
					left: 'center',
					textStyle: {
						fontSize: 14
					}
				},
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'shadow'
					}
				},
				legend: {
					data: ['总题数', '正确数'],
					top: 30
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				xAxis: {
					type: 'category',
					data: typeNames,
					axisLabel: {
						interval: 0,
						rotate: 30
					}
				},
				yAxis: {
					type: 'value'
				},
				series: [
					{
						name: '总题数',
						type: 'bar',
						data: totalData,
						itemStyle: {
							color: '#1890ff'
						}
					},
					{
						name: '正确数',
						type: 'bar',
						data: correctData,
						itemStyle: {
							color: '#52c41a'
						}
					}
				]
			};

			this.charts.typeChart.setOption(option);
		},
		// 初始化能力雷达图
		initRadarChart() {
			const chartDom = document.getElementById('radarChart');
			if (!chartDom) return;

			this.charts.radarChart = echarts.init(chartDom);

			const indicator = this.examResult.abilityData.map(item => {
				return { name: item.name, max: 100 };
			});

			const option = {
				color: ['#722ed1'],
				title: {
					text: '能力维度分析',
					left: 'center',
					textStyle: {
						fontSize: 14
					}
				},
				tooltip: {
					trigger: 'item'
				},
				radar: {
					indicator: indicator,
					shape: 'circle',
					splitNumber: 5,
					axisName: {
						color: '#333'
					},
					splitLine: {
						lineStyle: {
							color: ['#ddd']
						}
					},
					splitArea: {
						show: true,
						areaStyle: {
							color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.1)']
						}
					}
				},
				series: [{
					name: '能力分布',
					type: 'radar',
					data: [{
						value: this.examResult.abilityData.map(item => item.score),
						name: '能力分布'
					}],
					areaStyle: {
						opacity: 0.6
					}
				}]
			};

			this.charts.radarChart.setOption(option);
		},
		// 格式化题目标题
		formatTitle(title) {
			if (typeof title === 'string') {
				return title;
			} else if (Array.isArray(title)) {
				return title.join('');
			} else {
				return String(title || '');
			}
		},

		// 格式化时间
		formatTime(seconds) {
			if (!seconds) return '0秒';

			const minutes = Math.floor(seconds / 60);
			const remainingSeconds = seconds % 60;

			if (minutes > 0) {
				return `${minutes}分${remainingSeconds}秒`;
			} else {
				return `${remainingSeconds}秒`;
			}
		},

		// 跳转到AI聊天页面
		goToChat() {
			uni.navigateTo({
				url: `/pages/chat/chat?examId=${this.examId}&context=exam_result`
			});
		},

		// 分享结果
		shareResult() {
			uni.showToast({
				title: '分享功能开发中',
				icon: 'none'
			});
		},

		// 返回首页
		goHome() {
			uni.reLaunch({
				url: '/pages/index/index'
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.result-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding-bottom: 120rpx;
}

.nav-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}



.ability-list {
	margin-top: 20rpx;
}
.ability-item {
	background: #f6f8ff;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 8rpx rgba(24,144,255,0.06);
	margin-bottom: 24rpx;
	padding: 24rpx 28rpx 18rpx 28rpx;
	transition: box-shadow 0.2s;
}
.ability-item:last-child {
	margin-bottom: 0;
}
.ability-header {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
}
.ability-name {
	font-size: 30rpx;
	font-weight: 500;
	color: #333;
	margin-right: 16rpx;
}
.ability-score {
	font-size: 28rpx;
	color: #1890ff;
	font-weight: bold;
	margin-left: auto;
}
.ability-bar-bg {
	width: 100%;
	height: 14rpx;
	background: #e6f7ff;
	border-radius: 8rpx;
	overflow: hidden;
	margin-bottom: 8rpx;
}
.ability-bar {
	height: 100%;
	border-radius: 8rpx;
	transition: width 0.5s;
}
.ability-desc {
	font-size: 24rpx;
	color: #888;
	margin-top: 6rpx;
}

.score-card {
	position: relative;
	margin: 30rpx;
	height: 300rpx;
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

	.score-bg {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: 1;
	}

	.score-content {
		position: relative;
		z-index: 2;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
		background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.5));

		.score-title {
			font-size: 32rpx;
			margin-bottom: 20rpx;
		}

		.score-value {
			font-size: 80rpx;
			font-weight: bold;
			margin-bottom: 10rpx;

			.score-total {
				font-size: 40rpx;
				opacity: 0.8;
			}
		}

		.score-percent {
			font-size: 36rpx;
			margin-bottom: 20rpx;
		}

		.score-rank {
			font-size: 28rpx;
			background-color: rgba(255, 255, 255, 0.2);
			padding: 8rpx 20rpx;
			border-radius: 30rpx;

			.rank-value {
				font-weight: bold;
			}
		}
	}
}

.section-title,
.overview-title {
	display: flex;
	align-items: center;
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 20rpx;
	padding: 0 30rpx;

	.title-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}
}

.analysis-overview,
.time-analysis,
.question-type-analysis,
.ability-analysis,
.ai-suggestion,
.wrong-questions {
	margin: 30rpx;
	padding: 30rpx 0;
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.overview-cards {
	display: flex;
	justify-content: space-around;
	padding: 20rpx 0;

	.overview-card {
		display: flex;
		flex-direction: column;
		align-items: center;

		.card-value {
			font-size: 40rpx;
			font-weight: bold;
			color: #1890ff;
			margin-bottom: 10rpx;
		}

		.card-label {
			font-size: 26rpx;
			color: #666;
		}

		&:nth-child(2) .card-value {
			color: #52c41a;
		}

		&:nth-child(3) .card-value {
			color: #ff4d4f;
		}

		&:nth-child(4) .card-value {
			color: #722ed1;
		}
	}
}

.chart-container {
	padding: 0 20rpx;

	.chart-wrapper {
		width: 100%;
		height: 500rpx;
	}
}

.time-stats {
	margin-top: 20rpx;
	padding: 0 30rpx;

	.time-stat-item {
		display: flex;
		margin-bottom: 10rpx;

		.stat-label {
			font-size: 28rpx;
			color: #666;
			width: 200rpx;
		}

		.stat-value {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}
	}
}

.ai-suggestion {
	.suggestion-content {
		display: flex;
		padding: 0 30rpx;

		.ai-avatar {
			width: 80rpx;
			height: 80rpx;
			margin-right: 20rpx;
			flex-shrink: 0;
		}

		.suggestion-text {
			flex: 1;

			.suggestion-item {
				margin-bottom: 16rpx;
				font-size: 28rpx;
				color: #333;
				line-height: 1.5;
			}

			.suggestion-summary {
				margin-top: 20rpx;
				padding-top: 20rpx;
				border-top: 2rpx dashed #eee;
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
			}
		}
	}

	.ai-chat-btn-container {
		padding: 20rpx 30rpx 10rpx 30rpx;
		display: flex;
		justify-content: center;
	}

	.ai-chat-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 25rpx;
		padding: 16rpx 32rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.4);
		transition: all 0.3s;

		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
		}

		.chat-icon {
			width: 32rpx;
			height: 32rpx;
			margin-right: 12rpx;
		}

		text {
			color: #fff;
			font-size: 28rpx;
			font-weight: 500;
		}
	}
}

.wrong-list {
	padding: 0 30rpx;

	.wrong-item {
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #f0f0f0;

		&:last-child {
			margin-bottom: 0;
			border-bottom: none;
		}

		.wrong-title {
			font-size: 30rpx;
			color: #333;
			line-height: 1.5;
			margin-bottom: 16rpx;

			.wrong-number {
				font-weight: bold;
				color: #ff4d4f;
			}
		}

		.wrong-analysis {
			display: flex;
			margin-bottom: 10rpx;

			.analysis-label {
				font-size: 28rpx;
				color: #666;
				width: 120rpx;
				flex-shrink: 0;
			}

			.analysis-content {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				line-height: 1.5;

				&.wrong {
					color: #ff4d4f;
				}
			}
		}
	}
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	height: 100rpx;
	background-color: #fff;
	border-top: 2rpx solid #eee;

	.action-btn {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
	}

	.share-btn {
		background-color: #f5f5f5;
		color: #333;
	}

	.home-btn {
		background-color: #1890ff;
		color: #fff;
	}
}
</style>
